package com.yupi.springbootinit.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.mini.GenWxChartRequest;
import com.yupi.springbootinit.model.dto.user.UserLoginRequest;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.model.vo.MiniloginVO;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.service.impl.YouxiServiceImpl;
import com.yupi.springbootinit.utils.JwtUtil;
import com.yupi.springbootinit.utils.ThreadLocalUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * 微信小程序相关接口
 * @Author xingyu Xue
 * @Date 2024/3/25 21:05
 */
@RestController
//@AllArgsConstructor
@RequestMapping("/wxmini")
@Slf4j
public class WxMiniController {
    private final  WxMaService wxMaService;
     //构造器注入WxMaService 依赖
    @Autowired
    public WxMiniController(WxMaService wxMaService) {
        this.wxMaService = wxMaService;
    }

    @Value("${wx.miniapp.configs[0].appid}")
    private String appid;




    @Resource
    private UserService userService;
    @Resource
    private YouxiServiceImpl youxiServicel;



    @GetMapping("/test")
    public BaseResponse<String> test() {

        return ResultUtils.success("test");
    }



    @GetMapping("/login")
    public BaseResponse<String> userLogin(  String code,HttpServletRequest request) {
        log.info("login接口~~~");
        if (StringUtils.isBlank(code)) {
            return new BaseResponse<>("empty jscode");
        }
        //判断appid是否存在
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            //向腾讯接口发送code请求，
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();
            String sessionKey = session.getSessionKey();
            String unionid = session.getUnionid();
            log.info("sessionKey:{}",sessionKey);
            log.info("openid:{}",openid);
            //TODO 可以增加自己的逻辑，关联业务相关数据
            MiniloginVO miniloginVO = userService.miniLogin(openid, sessionKey);
            log.info(miniloginVO.toString());
            //生成返回给小程序的token
            Map<String,Object> map = new HashMap();
            map.put("openid",miniloginVO.getOpenid());
            map.put("userid",miniloginVO.getId());
            map.put("username",miniloginVO.getUserName());

            String token = JwtUtil.genToken(map);
            if (token!=null){
                log.info("token:{}",token);
            }


            return new BaseResponse<>(100,token,"登录成功");


        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return new BaseResponse<>(e.toString());

//            return e.toString();
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }


    }

    @ApiOperation(value = "获取用户信息", notes = "需要提供有效的 JWT token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "JWT token", required = true, dataType = "string", paramType = "header")
    })
    @PostMapping("/zimi/dataupload")
    public BaseResponse dataupload(@RequestBody String data, HttpServletRequest request){
        log.info("dataupload接口~~~");
        log.info("data:{}",data);

        //从threadlocal中看里面存储了哪些数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Long id = (Long) map.get("userid");
        log.info("userid:{}",id);
        String openid = (String) map.get("openid");
        log.info("openid:{}",openid);
        String username = (String) map.get("username");
        log.info("username:{}",username);


        return new BaseResponse<>(100,"上传成功");



    }


    @PostMapping("/gen")
    public BaseResponse<String> genChart(@RequestBody GenWxChartRequest genWxChartRequest, HttpServletRequest request){
        String startTime = genWxChartRequest.getStartTime();
        String endTime = genWxChartRequest.getEndTime();

        String s = youxiServicel.tableToChart(startTime, endTime);

        return null;
    }

}
